package edu.nf.project.services.storeOperation.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import edu.nf.project.entitys.entity.storeOperation.convention.dish.Dish;
import edu.nf.project.entitys.entity.storeOperation.convention.dish.DishType;
import edu.nf.project.entitys.entity.storeOperation.convention.operate.CustomerOrder;
import edu.nf.project.entitys.entity.storeOperation.convention.operate.CustomerOrderItem;
import edu.nf.project.entitys.enums.storeOperation.DishStatusEnum;
import edu.nf.project.entitys.enums.storeOperation.OrderStatusEnum;
import edu.nf.project.mappers.storeOperation.convention.*;
import edu.nf.project.services.exception.derivedAnomalies.CustomerOrderException;
import edu.nf.project.services.response.ResultVO;
import edu.nf.project.services.storeOperation.DishDTOService;
import edu.nf.project.services.storeOperation.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 菜品服务实现类
 */
@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishDTOMapper dishDTOMapper;

    @Autowired
    private DishTypeMapper dishTypeMapper;

    @Autowired
    private CustomerOrderItemMapper customerOrderItemMapper;

    @Autowired
    private CustomerOrderMapper customerOrderMapper;

    @Override
    public List<Dish> getDishList() {
        return dishMapper.getDishList();
    }

    @Override
    public Page<Dish> getDishList(Page<Dish> page, String dishName, Integer dtId) {
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 根据菜品名称模糊查询
        if (StringUtils.hasText(dishName)) {
            queryWrapper.like(Dish::getDishName, dishName);
        }
        // 根据菜品类型查询
        if (dtId != null) {
            queryWrapper.eq(Dish::getDtId, dtId);
        }
        // 按菜品ID倒序排序
        queryWrapper.orderByDesc(Dish::getDishId);
        return dishMapper.selectPage(page, queryWrapper);
    }

    @Override
    public Dish getDishInfo(Integer dishId) {
        return dishMapper.selectById(dishId);
    }

    @Override
    @Transactional
    public boolean createDish(Dish dish) {
        // 设置默认状态为出售
        dish.setDishStatus(DishStatusEnum.SELL);
        return dishMapper.insert(dish) > 0;
    }

    @Override
    @Transactional
    public boolean updateDish(Integer dishId, Dish dish) {
        dish.setDishId(dishId);
        return dishMapper.updateById(dish) > 0;
    }

    @Override
    @Transactional
    public boolean updateDishStatus(Integer dishId, DishStatusEnum status) {
        Dish dish = new Dish();
        dish.setDishId(dishId);
        dish.setDishStatus(status);
        return dishMapper.updateById(dish) > 0;
    }

    @Override
    public String getDishType(Integer dishId) {
        Dish dish = dishMapper.selectById(dishId);
        if (dish == null) {
            return null;
        }
        DishType dishType = dishTypeMapper.selectById(dish.getDtId());
        if (dishType == null) {
            return null;
        }
        return dishType.getDtName();
    }

    @Override
    public String[] getDishTypes() {
        List<DishType> dishType = dishTypeMapper.selectList(null);
        if (dishType == null) {
            return null;
        }
        List<String> dtNames = new ArrayList<>();
        for (DishType dt : dishType) {
            dtNames.add(dt.getDtName());
        }
        return dtNames.toArray(new String[0]);
    }

    @Override
    public List<DishType> getAllDishTypes() {
        return dishTypeMapper.selectList(null);
    }

    @Override
    public Boolean delDishType(Integer dtId) {
        DishType dt = new DishType();
        dt.setDtId(dtId);
        return dishTypeMapper.deleteById(dt) > 0;
    }

    @Override
    public Boolean addDishType(String dt) {
        DishType obj = new DishType();
        obj.setDtName(dt);
        return dishTypeMapper.insert(obj) > 0;
    }

    @Override
    public Boolean updDishType(Integer dt, String name) {
        DishType obj = new DishType();
        obj.setDtId(dt);
        obj.setDtName(name);
        return dishTypeMapper.updateById(obj) > 0;
    }

    @Override
    public List<Dish> getAllDish() {
        return dishMapper.selectList(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean returnDish(Integer orderId, Integer dishId) {
        // 1. 检查订单是否存在且状态是否允许退菜
        CustomerOrder order = customerOrderMapper.selectById(orderId);
        if (order == null) {
            throw new CustomerOrderException(50005, "订单不存在");
        }
        if (order.getOrderStatus() == OrderStatusEnum.PAID) {
            throw new CustomerOrderException(50006, "已支付的订单不能退菜");
        }
        if (order.getOrderStatus() == OrderStatusEnum.CANCELED) {
            throw new CustomerOrderException(50007, "已取消的订单不能退菜");
        }

        // 2. 查找并删除订单项
        LambdaQueryWrapper<CustomerOrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerOrderItem::getOrderId, orderId)
                   .eq(CustomerOrderItem::getDishId, dishId);
        
        int result = customerOrderItemMapper.delete(queryWrapper);
        if (result <= 0) {
            throw new CustomerOrderException(50008, "退菜失败，未找到对应的菜品");
        }

        return true;
    }

    /**
     * 定时任务
     */
    @Override
    @Transactional
    public void optimizeDishPriority() {
        // 第一步：查询销量最高的前 5 个菜品 ID
        List<Integer> top5Ids = dishDTOMapper.findTop5DishIdsBySales();

        if (top5Ids == null || top5Ids.isEmpty()) {
            return; // 没有销量数据，直接退出
        }

        // 第二步：将这些菜品的优先级设置为 1（最高）
        dishDTOMapper.updatePriorityBatch(top5Ids, 1);

        // 第三步：把优先级=1但不在前5名的菜品恢复为 3
        dishDTOMapper.resetOldTopPriority(top5Ids);
    }
}